package cn.lx.auth.secutity.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @ClassName SpringContextUtils
 * @Description: //todo
 * @Author: 落雪
 * @CreateDate: 2025/7/14 23:26
 * @UpdateUser: 落雪
 * @UpdateDate: 2025/7/14 23:26
 * @UpdateRemark:
 * @Version: 1.0
 */
@Component
public class SpringContextUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    private static final Log LOGGER = LogFactory.getLog(SpringContextUtils.class);

    public SpringContextUtils() {
    }

    public static void setContext(ApplicationContext context) {
        applicationContext = context;
    }

    @Override
    public void setApplicationContext(ApplicationContext context) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("SpringContextUtil注入applicaitonContext");
        }

        setContext(context);
    }

    public static ApplicationContext getApplicationContext() {
        return hasLoadContext() ? applicationContext : null;
    }

    public static  Object getBean(String name) {
        return hasLoadContext() ? applicationContext.getBean(name) : null;
    }

    private static boolean hasLoadContext() {
        if (applicationContext == null) {
            throw new IllegalStateException("SpringContextUtil初始化失败,请在applicationContext.xml中定义SpringContextUtil");
        } else {
            return true;
        }
    }

    public static boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }
}

